package com.home.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.classic.Session;
import org.springframework.dao.DataAccessException;

import com.home.common.AbstractDaoSupport;
import com.home.entity.User;

public class UserDaoImpl extends AbstractDaoSupport implements UserDao{
	/**
	 * 添加用户
	 */
	public int addUser(User user){
		Session session = super.getSessionFactory().getCurrentSession();
		session.save(user);
		if(user.getUserId() != null && !"".equals(user.getUserId())){
			return 1;
		}
		return 0;
	}
	
	/**
	 * 查询用户
	 */
	public User findUserByNameAndPassword(String username, String passsord) {
		String sql = "select * from USER where username = ? and password = ?";
		Session session = super.getSessionFactory().getCurrentSession();
		Query query = session.createSQLQuery(sql);
		int index = 0;
		query.setString(index++, username);
		query.setString(index++, passsord);
		return (User) query.uniqueResult();
	}
	
	/**
     * 通过邮箱 或者用户名登陆
     * @param user
     * @return
     * @throws DataAccessException
     */
    public User findUserByUser(User user) {
        String hql = "from User u where (u.userName = ? or u.email = ?) and passWord = ?";
        Session session = super.getSessionFactory().getCurrentSession();
        Query query = session.createQuery(hql);
        int index = 0;
        query.setString(index++, user.getUserName());
        query.setString(index++, user.getUserName());
        query.setString(index++, user.getPassWord());
        return (User) query.uniqueResult();
    }
	
	/**
	 * 查询所有User 集合
	 * @return
	 */
	public List<User> getAllUser(){
		return null;
	}
}
